<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编码" prop="innerCode">
        <el-input v-model="queryParams.innerCode" placeholder="请输入设备编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="区域ID" prop="regionId">
        <el-input
          v-model="queryParams.regionId"
          placeholder="请输入区域ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合作商ID" prop="partnerId">
        <el-input
          v-model="queryParams.partnerId"
          placeholder="请输入合作商ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型ID" prop="vmTypeId">
        <el-input
          v-model="queryParams.vmTypeId"
          placeholder="请输入设备类型ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="vmStatus">
        <el-select v-model="queryParams.vmStatus" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in dict.type.vm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['manager:vm:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manager:vm:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manager:vm:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['manager:vm:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="设备ID" align="center" prop="id" /> -->
      <el-table-column label="设备编码" align="center" prop="innerCode" />
      <!-- <el-table-column label="上次补货时间" align="center" prop="lastSupplyTime" width="180">
        <template slot-scope="scope">
          <span>{{ this.parseTime(scope.row.lastSupplyTime) }}</span> -->
      <!-- <span>{{ parseTime(scope.row.lastSupplyTime, '{y}-{m}-{d}') }}</span> -->
      <!-- </template>
</el-table-column> -->
      <el-table-column label="设备型号" align="center" prop="vmTypeId">
        <template slot-scope="scope">
          <div v-for="item in vmTypeList" :key="item.id">
            <span v-if="item.id == scope.row.vmTypeId">{{ item.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备地址" align="center" prop="addr" show-overflow-tooltip="true" />
      <!-- <el-table-column label="区域" align="center" prop="regionId" /> -->
      <el-table-column label="合作商" align="center" prop="partnerId">
        <template slot-scope="scope">
          <div v-for="item in partnerList" :key="item.id">
            <span v-if="item.id == scope.row.partnerId">{{ item.partnerName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="vmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.vm_status" :value="scope.row.vmStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdatePolicy(scope.row)"
            v-hasPermi="['manager:vm:edit']">策略</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:vm:edit']">修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manager:vm:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备编码" prop="innerCode">
          <!-- 三元运算符,如果为空,则为系统自动生成 -->
          <span>{{ form.innerCode == null ? '系统自动生成' : form.innerCode }}</span>
          <!-- <el-input v-model="form.innerCode" placeholder="请输入设备编码" /> -->
        </el-form-item>
        <el-form-item label="供货时间" v-if="form.innerCode == null">
          <span>{{ formatDateTime(new Date()) }}</span>
          <!-- <el-date-picker v-model="form.lastSupplyTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"/> -->

        </el-form-item>
        <!-- <span>{{ praseTime(form.lastSupplyTime, " {y}-{m}-{d} {h}:{i}:{s}") }}</span> -->
        <el-form-item label="设备类型" v-if="form.innerCode == null">
          <div v-for="item in vmTypeList" :key="item.id">
            <span v-if="item.id == form.vmTypeId">{{ item.name }}</span>
          </div>
        </el-form-item>

        <el-form-item label="设备容量" v-if="form.innerCode == null">
          <span>{{ form.channelMaxCapacity }}</span>
        </el-form-item>

        <el-form-item label="选择型号" prop="vmTypeId" v-if="form.innerCode == null">
          <el-select v-model="form.vmTypeId" placeholder="请选择设备型号">
            <el-option v-for="item in vmTypeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <!-- <el-input v-model="form.vmTypeId" placeholder="请选择设备型号" /> -->
        </el-form-item>
        <el-form-item label="请选择点位" prop="nodeId">
          <el-select v-model="form.nodeId" placeholder="请选择点位">
            <el-option v-for="item in nodeList" :key="item.id" :label="item.nodeName" :value="item.id" />
          </el-select>
          <!-- <el-input v-model="form.nodeId" placeholder="请选择点位" /> -->
        </el-form-item>

        <el-form-item label="合作商" v-if="form.innerCode == null">
          <div v-for="item in partnerList" :key="item.id">
            <span v-if="item.id == form.partnerId">{{ item.partnerName }}</span>
          </div>
        </el-form-item>

        <el-form-item label="所属区域" v-if="form.innerCode == null">
          <div v-for="item in regionList" :key="item.id">
            <span v-if="item.id == form.regionId">{{ item.regionName }}</span>
          </div>
        </el-form-item>

        <el-form-item label="设备地址" v-if="form.innerCode == null">
          <span>{{ form.addr }}</span>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 设备策略分配弹窗 -->
     <el-dialog :title="title" :visible.sync="policyOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form"  label-width="120px">
        <el-form-item label="选择策略">
          <el-select v-model="form.policyId" placeholder="请选择策略">
            <el-option v-for="item in policyList" :key="item.id" :label="item.policyName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      </el-dialog>
  </div>
</template>

<script>
import { listVm, getVm, delVm, addVm, updateVm } from "@/api/manager/vm.js";
import { listVmType } from "@/api/manager/vmType";
import { listPartner } from "@/api/manager/partner";
import { loadAllParams } from "@/api/page"
import { listNode } from "@/api/manager/node"
import { listRegion } from "@/api/manager/region";
import { listPolicy } from "@/api/manager/policy"
import dayjs from "dayjs";


export default {
  name: "Vm",
  dicts: ['vm_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      vmList: [],
      // 策略列表
      policyList: [],
      // 策略弹窗
      policyOpen: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        innerCode: null,
        businessType: null,
        regionId: null,
        partnerId: null,
        vmTypeId: null,
        vmStatus: null,
        runningStatus: null,
      },
      // 设备类型列表
      vmTypeList: [],
      // 合作商列表
      partnerList: [],
      // 点位列表
      nodeList: [],
      // 区域列表
      regionList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // innerCode: [
        //   { required: true, message: "设备编码不能为空", trigger: "blur" }
        // ],
        nodeId: [
          { required: true, message: "点位id不能为空", trigger: "blur" }
        ],
        vmTypeId: [
          { required: true, message: "设备类型ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();

  },
  mounted() {
    this.getVmType();
    this.getPartner();
    this.getNode();
    this.getRegion();
  },
  methods: {
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listVm(this.queryParams).then(response => {
        this.vmList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.policyOpen = false; // 关闭策略弹窗
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        innerCode: null,
        channelMaxCapacity: null,
        addr: null,
        lastSupplyTime: null,
        businessType: null,
        regionId: null,
        partnerId: null,
        vmTypeId: null,
        vmStatus: null,
        runningStatus: null,
        longitude: null,
        latitude: null,
        clientId: null,
        policyId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /* 设备策略分配 */
    handleUpdatePolicy(row) {
      // 为表单赋值设备id和策略id
      form.id = row.id;
      form.policyId = row.policyId;
      // 2.查询策略列表
      listPolicy(loadAllParams).then(response => {
        this.policyList = response.rows;
        // 3.打开弹窗
        this.policyOpen = true;
      })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVm(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVm(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.policyOpen = false; // 关闭策略弹窗
              this.getList();
            });
          } else {
            addVm(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + ids + '"的数据项？').then(function () {
        return delVm(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manager/vm/export', {
        ...this.queryParams
      }, `vm_${new Date().getTime()}.xlsx`)
    },

    /* 查询设备类型列表 */
    getVmType() {
      listVmType(loadAllParams).then(response => {
        this.vmTypeList = response.rows;
      });
    },
    /* 查询合作商列表 */
    getPartner() {
      listPartner(loadAllParams).then(response => {
        this.partnerList = response.rows;
      });
    },
    // 查询点位列表
    getNode() {
      listNode(loadAllParams).then(response => {
        this.nodeList = response.rows;
      });
    },
    // 查询区域列表
    getRegion() {
      listRegion(loadAllParams).then(response => {
        this.regionList = response.rows;
      });
    },
    formatDateTime(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    }
  }
};
</script>
